# -*- coding: UTF-8 -*-
# from django.shortcuts import render
from queue import Queue
from unicodedata import name  # 实现收藏夹的队列功能
from branch.dataCheck import DataCheck, WechatApi
from django.core.serializers.json import json
from multiprocessing.dummy import JoinableQueue
from django.http import JsonResponse
import os
import pdb
import json
from user.models import *
from branch.models import *
import logging
logger = logging.getLogger("userlog")
logger_request = logging.getLogger("django.request")


dataCheck = DataCheck()
wechatApi = WechatApi()
q = Queue(maxsize=15)
# Create your views here.
# pdb.set_trace()


def test1(request, *args, **kwargs):
    """
    @url:
        /user/test1
    """
    data = {
        "code": 0,
        "msg": "success",
    }
    # pdb.set_trace()
    return JsonResponse(data)

# 生成邀请码


def generateInviteCode(request, *args, **kwargs):
    """
        url    : /user/generate/
        method : GET

    :param request:


    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
              'inviteCode'   //生成的邀请码
    """
    inviteCode = dataCheck.getLocalToken()
    inviteCode = inviteCode.upper()[:6]
    invite = InviteCode.objects.create(
        inviteCode=inviteCode
    )
    data = {
        "code": 0,
        "msg": 'success',
        "inviteCode": invite.inviteCode
    }
    return JsonResponse(data)

# 注册


def signup(request, *args, **kwargs):
    """
        url    : /user/signup/
        method : POST

    :param request:
                inviteCode
                phone
                password

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    invitecode = requestParam['inviteCode']
    phone = requestParam['phone']
    password = requestParam['password']
    invite = InviteCode.objects.filter(inviteCode=invitecode)
    data = {
        'code': 1,  # 标志返回状态、0：成功 1：失败
        'msg': 'error',  # 返回消息
    }
    # pdb.set_trace()
    if len(invite) != 0:
        if not invite[0].isUsed:
            account = AccountInfo.objects.filter(username=phone)
            if len(account) == 0:
                user = UserInfo.objects.create(  # 只根据手机号创建用户，后续再进行更新
                    phone=phone,
                )
                account = AccountInfo.objects.create(  # 添加账户密码信息
                    username=phone,
                    userpwd=password,
                    userInfo=user,
                )
                data = {
                    'code': 0,  # 标志返回状态、0：成功 1：失败
                    'msg': 'success',  # 返回消息
                }
                InviteCode.objects.filter(
                    inviteCode=invitecode).update(isUsed=True)  # 更新邀请码
            else:
                data = {
                    'code': 1,  # 标志返回状态、0：成功 1：失败
                    'msg': 'existed',  # 返回消息
                }
    return JsonResponse(data)


# 不用微信的登录
def loginnowx(request, *args, **kwargs):
    """
        url    : /user/loginnowx/
        method : POST

    :param request:
                username  // 登录账户
                userpwd   // 登录密码

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'token': null, // token
                'userType': null, // 用户类型，新注册用户这项为'' 党员 积极分子
                'name':null, //用户真实姓名
                'phone':null,
                'gender':null,
                'stuNum':null,
                'classNum':null,
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    username = requestParam['username']
    userpwd = requestParam['userpwd']
    # pdb.set_trace()
    try:
        account = AccountInfo.objects.get(
            username=username, userpwd=userpwd)  # 如果能查到，说明有信息
        accountinfo = AccountInfo.objects.filter(
            username=username).values()[0]  # 返回的是字典
        userinfo = UserInfo.objects.get(id=accountinfo['userInfo_id'])
        user = UserInfo.objects.filter(
            id=accountinfo['userInfo_id']).values()[0]
        zsdy = ZSDYList.objects.filter(name=user['id'])
        jjfz = JJFZList.objects.filter(name=user['id'])
        ybdy = YBDYList.objects.filter(name=user['id'])
        if len(jjfz) != 0:  # 如果积极分子名单中有该成员，则在积极分子表中查询
            user['branch'] = UserInfo.objects.filter(id=accountinfo['userInfo_id'])[
                0].jjfzlist.branch.branch
            dev1, dev2 = UserInfo.objects.filter(
                id=accountinfo['userInfo_id']).first().jjfzlist.devPeo.all()
            user['devPeo1'] = dev1.name.name + '-' + dev1.name.stuNum
            user['devPeo2'] = dev2.name.name + '-' + dev2.name.stuNum
        elif len(ybdy) != 0:  # 如果预备党员名单中有该成员，则在预备党员中查询
            user['branch'] = UserInfo.objects.filter(id=accountinfo['userInfo_id'])[
                0].ybdylist.branch.branch
            dev1, dev2 = UserInfo.objects.filter(
                id=accountinfo['userInfo_id']).first().ybdylist.devPeo.all()
            user['devPeo1'] = dev1.name.name + '-' + dev1.name.stuNum
            user['devPeo2'] = dev2.name.name + '-' + dev2.name.stuNum
        elif len(zsdy) != 0:  # 如果预备党员名单中有该成员，则在正式党员中查询
            user['branch'] = UserInfo.objects.filter(id=accountinfo['userInfo_id'])[
                0].zsdylist.branch.branch
        vsession = VSession.objects.create(
            token=dataCheck.getLocalToken(),
            userInfo=userinfo,
        )
        data = {
            'code': 0,
            'msg': 'success',
            'token': vsession.token,
            'userInfo': user
        }
    except:
        data = {
            'code': 1,
            'msg': 'error',
        }
    # pdb.set_trace()
    return JsonResponse(data)


def changePassword(request, *args, **kwargs):
    """
        url    : /user/updatezsdy/
        method : POST

    :param request:
            token:data.token,
            oldPassword:data.oldPassword,
            newPassword:data.newPassword,

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    # 单条数据更新 个人信息
    user = dataCheck.getUser(requestParam)
    oldPassword = requestParam['oldPassword']
    databasePwd = user.accountinfo.userpwd
    if oldPassword == databasePwd:
        user.accountinfo.userpwd = requestParam['newPassword']
        user.accountinfo.save()
        data = {
            'code': 0,
            'msg': 'success',
        }
    else:
        data = {
            'code': 1,
            'msg': 'error',
        }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


# 更新党员信息
def updatezsdy(request, *args, **kwargs):
    """
        url    : /user/updatezsdy/
        method : POST

    :param request:
                token
                name
                classNum
                stuNum
                phone
                branch
                userType

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    # 单条数据更新 个人信息
    # pdb.set_trace()
    user = dataCheck.getUser(requestParam)
    user.name = requestParam['name']
    user.classNum = requestParam['classNum']
    user.stuNum = requestParam['stuNum']
    user.phone = requestParam['phone']
    user.userType = requestParam['userType']
    user.save()
    # 更新正式党员信息
    zsdy = ZSDYList.objects.filter(name=user.id)
    jjfz = JJFZList.objects.filter(name=user.id)
    ybdy = YBDYList.objects.filter(name=user.id)
    branch = BranchInfo.objects.get(branch=requestParam['branch'])
    if len(jjfz) != 0:  # 如果积极分子名单中有该成员，则删除
        jjfz.delete()
    if len(ybdy) != 0:  # 如果预备党员名单中有该成员，则删除
        ybdy.delete()
    if len(zsdy) != 0:  # 如果正式党员名单中有该成员，则更新
        zsdy = zsdy.first()
        zsdy.name = user
        zsdy.branch = branch
        zsdy.save()
    elif len(zsdy) == 0:  # 如果之前没有信息，则创建
        dy = ZSDYList.objects.create(
            name=user,
            branch=branch,
        )
    data = {
        'code': 0,
        'msg': 'success',
    }
    return JsonResponse(data)

# 更新预备党员、积极分子信息


def updateOther(request, *args, **kwargs):
    """
        url    : /user/updateother/
        method : POST

    :param request:
                token
                name
                classNum
                stuNum
                phone
                branch
                userType

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    # 单条数据更新 个人信息
    user = dataCheck.getUser(requestParam)
    user.name = requestParam['name']
    user.classNum = requestParam['classNum']
    user.stuNum = requestParam['stuNum']
    user.phone = requestParam['phone']
    user.userType = requestParam['userType']
    user.save()

    zsdy = ZSDYList.objects.filter(name=user.id)
    jjfz = JJFZList.objects.filter(name=user.id)
    ybdy = YBDYList.objects.filter(name=user.id)
    # pdb.set_trace()
    name1, stuNum1 = requestParam['devPeo1'].split('-')
    name2, stuNum2 = requestParam['devPeo2'].split('-')
    # 获取两名正式党员信息 一对一反向查询不用加_set
    dev1 = UserInfo.objects.filter(stuNum=stuNum1, name=name1).first().zsdylist
    dev2 = UserInfo.objects.filter(stuNum=stuNum2, name=name2).first().zsdylist
    # 获取支部信息
    branch = BranchInfo.objects.get(branch=requestParam['branch'])
    # 如果积极分子名单中有该成员，则删除
    if len(jjfz) != 0 and requestParam['userType'] == '积极分子':
        jjfz = jjfz.first()
        jjfz.name = user
        jjfz.branch = branch
        jjfz.devPeo.clear()  # 将以前的培养联系人删除
        jjfz.devPeo.add(dev1, dev2)  # 添加现在的培养联系人
        jjfz.save()
    # 如果预备党员名单中有该成员，则删除
    elif len(ybdy) != 0 and requestParam['userType'] == '预备党员':
        ybdy = ybdy.first()
        ybdy.name = user
        ybdy.branch = branch
        ybdy.devPeo.clear()  # 将以前的培养联系人删除
        ybdy.devPeo.add(dev1, dev2)  # 添加现在的培养联系人
        ybdy.save()
    elif requestParam['userType'] == '积极分子':  # 如果是增积极分子
        jj = JJFZList.objects.create(
            name=user,
            branch=branch,
        )
        jj.devPeo.add(dev1, dev2)
    elif requestParam['userType'] == '预备党员':  # 如果是增预备党员
        yb = YBDYList.objects.create(
            name=user,
            branch=branch,
        )
        yb.devPeo.add(dev1, dev2)
    if len(zsdy) != 0:  # 如果正式党员名单中有该成员，则删除
        zsdy.delete()
    data = {
        'code': 0,
        'msg': 'success',
    }
    return JsonResponse(data)


# 微信登录
def login(request, *args, **kwargs):
    """
        url    : /user/login/
        method : POST

    :param request:
               code

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
              'token'        // token
              'userType'     // 用户类型
              'name'         // 姓名
              'avatar'       // avatar Url todo 不知是什么
    """
    # pdb.set_trace()
    form = request.checkForm
    requestParam = form.cleaned_data
    code = requestParam['code']
    # 获取code 获取access token
    result = wechatApi.getAccesstoken(code)
    try:
        access_token = result['access_token']
        openid = result['openid']
        refresh_token = result['refresh_token']
    except:
        data = {
            'code': 1,
            'msg': result,
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    # print(access_token, openid, refresh_token)
    # pdb.set_trace()
    personal = wechatApi.getPerson(access_token, openid)
    print(personal)
    # 查看是否新用户
    # pdb.set_trace()
    user_in = UserInfo.objects.filter(openid=personal['openid'])
    # print(len(user_in))
    if len(user_in) == 1:
        # 老用户
        # pdb.set_trace()
        user = user_in[0]
        if user.nickname != personal['nickname']:
            user_nickname = UserInfo.objects.filter(
                id=user.id).update(nickname=personal['nickname'])
        if user.headimgurl != personal['headimgurl']:
            user_headimgurl = UserInfo.objects.filter(
                id=user.id).update(headimgurl=personal['headimgurl'])
        if user.userType == 0:  # 积极分子
            pass

        vsession = VSession.objects.create(
            token=dataCheck.getLocalToken(),
            userInfo=user,
        )
        userType = user.userType
    elif len(user_in) == 0:
        # 新用户
        if personal['sex'] == 1:
            gender = 'male'
        else:
            gender = 'female'
        try:
            user = UserInfo.objects.create(
                # phone=requestParam['phone'],
                nickname=personal['nickname'],
                unionid=personal['unionid'],
                openid=personal['openid'],
                access_token=access_token,
                refresh_token=refresh_token,
                headimgurl=personal['headimgurl'],
                gender=gender,
            )
        except KeyError:
            user = UserInfo.objects.create(
                # phone=requestParam['phone'],
                nickname=personal['nickname'],
                # unionid=personal['unionid'],
                openid=personal['openid'],
                access_token=access_token,
                refresh_token=refresh_token,
                headimgurl=personal['headimgurl'],
                gender=gender,
            )
        vsession = VSession.objects.create(
            token=dataCheck.getLocalToken(),
            userInfo=user,
        )
        userType = ''
    else:
        # 错误
        data = {
            'code': 1,
            'msg': 'The same unionid exists for different users of the database ',
            'requestParam': requestParam,
        }
        return JsonResponse(data)

    # pdb.set_trace()
    data = {
        "code": 0,
        "msg": "成功",
        "token": vsession.token,
        "stuNum": user.stuNum,
        "userType": userType,
        "name": user.name,
        "avatar": personal['headimgurl'],
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})

# 登出


def logout(request, *args, **kwargs):
    """
        url    : /user/logout/
        method : POST

    :param request:
               token          // 秘钥

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    vsession = VSession.objects.filter(
        userInfo=user).filter(token=requestParam['token'])
    vsession.delete()

    data = {
        "code": 0,
        "msg": "success",
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})

# 获得阿里云token


def getAliToken(request, *args, **kwargs):
    """
        @url:
            /user/practice/osstoken
        @input:
            token: data.token // 用户的秘钥
        @return:
            'code': null,
            'msg': mull,            
            'Alitoken': [{
                'region': null, // 地区
                'accessKeyId': null, // id
                'accessKeySecret': null, // secret
                'bucket': null, // 名称
            }]
    """
    form = request.checkForm
    requestParam = form.cleaned_data

    # pdb.set_trace()
    # 验证token
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    # aliTokenList = []
    aliList = Ali.objects.get(id=1)
    data = {
        'code': 0,
        'msg': 'success',
        'region': aliList.region,
        'accessKeyId': aliList.accessKeyId,
        'accessKeySecret': aliList.accessKeySecret,
        'bucket': aliList.bucket,
    }

    return JsonResponse(data)

# 获取党员名单


def getDY(request, *args, **kwargs):
    """
        url    : /user/getdy/
        method : POST

    :param request:
               token          // 秘钥
               branch         支部名称

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
              'dylist'       党员名单

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)

    # 主表查子表
    # 反向：对象.小写类名_set() 可以跳转到关联的表。
    members = BranchInfo.objects.filter(
        branch=requestParam['branch']).first().zsdylist_set.all()
    dylist = []
    # pdb.set_trace()
    for member in members:
        dylist.append(member.name.name+'-'+member.name.stuNum)
    data = {
        'code': 0,
        'msg': 'success',
        'dylist': dylist,
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})
    # return JsonResponse(data)
